package com.cqcet.wenchuang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqcet.wenchuang.entity.AddressBook;
import com.cqcet.wenchuang.entity.User;
import com.cqcet.wenchuang.mapper.AddressBookMapper;
import com.cqcet.wenchuang.service.AddressBookService;
import com.cqcet.wenchuang.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Autowired
    private UserService userService;

    /**
     * 根据用户id获取默认地址
     *
     * @param userId
     * @return
     */
    @Override
    public AddressBook getDefaultAddress(Long userId) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        //根据用户id查地址
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), AddressBook::getUserId, userId);
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        return this.getOne(queryWrapper);
    }

    /**
     * 保存为默认地址
     *
     * @param addressBookId
     */
    @Override
    public void saveAsDefault(Long addressBookId) {
        AddressBook book = this.getById(addressBookId);
        Long userId = book.getUserId();
        User user = userService.getById(userId);

        LambdaUpdateWrapper<AddressBook> queryWrapper = new LambdaUpdateWrapper<>();
        //将原来的默认地址清除
        if (ObjectUtils.isNotEmpty(user)) {
            throw new ClassCastException("修改失败");
        }
        queryWrapper.eq(AddressBook::getUserId, user.getId());
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        queryWrapper.set(AddressBook::getIsDefault, 0);
        this.update(null, queryWrapper);
        //设为默认地址
        book.setIsDefault(1);
        this.updateById(book);
    }
}
